package com.hc.hc_bot_kit

import android.content.Context
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.PermissionUtils
import com.robint.RosController
import com.robint.ros.utils.RosLocationUtils

enum class RobotMethod(rawValue: String) {

    connect("connect") {
        override fun invoke(
            call: MethodCall,
            result: MethodChannel.Result,
            context: Context
        ) {
            val args = call.arguments as? Map<String, Any>
            val ip = args?.get("ipAddress") ?: return result.error(
                "500",
                "can not get ipAddress in 'RobotMethod:connect'",
                null
            )
            PermissionUtils.permission(
                PermissionConstants.STORAGE
            ).request()
            rosMain.init(ip.toString(),context,{ b->
                GlobalScope.launch(Dispatchers.Main) {
                    result.success(b)
                }
            })
        }
    },

    guide("guide") {
        override fun invoke(
            call: MethodCall,
            result: MethodChannel.Result,
            context: Context
        ) {
            val args = call.arguments as? Map<String, Any>
            val destination = args?.get("destination") ?: return result.error(
                "500",
                "can not destination in 'RobotMethod:guide'",
                null
            )
            var ret = rosMain.navigationTo(destination.toString())
            result.success(ret)
        }
    },

    fetchAllPoints("fetchAllPoints") {
        override fun invoke(
            call: MethodCall,
            result: MethodChannel.Result,
            context: Context
        ) {
            var points = arrayListOf<String>()
            val mapList = RosLocationUtils.getRosMapList()
            var currentMapUuid = RosController.getInstance().getCurrentMappuid()

            val mapBean = mapList.find { rosMapBean ->
                rosMapBean.getMap_uuid() == currentMapUuid
            }
            mapBean?.let {
                for (e in it.loc_list) {
                    points.add(e.name)
                }
            }
            result.success(points)
        }
    },

    close("close") {
        override fun invoke(
            call: MethodCall,
            result: MethodChannel.Result,
            context: Context
        ) {
            result.success(null)
        }
    };

    abstract fun invoke(
        call: MethodCall,
        result: MethodChannel.Result,
        context: Context,
    )

    companion object {
        val rosMain = RosMain()
    }
}